package com.pingan.stat.money24.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.pingan.common.util.ShellExecutor;
import com.pingan.common.util.UrlParser;
import com.pingan.setting.money24url.entity.Money24UrlBean;
import com.pingan.setting.money24url.service.Money24UrlSettingService;

@Component
public class Money24UrlStatService {

	@Resource
	private Money24UrlSettingService money24UrlSettingService;

	@Resource
	private ShellExecutor shellExecutor;

	public void stat(String output, String money24UrlStatCreateHQLShell,
			String shell, String yyyyMMdd, Date date) {
		List<Money24UrlBean> beans = money24UrlSettingService
				.getStatMoney24Urls(date);

		for (Money24UrlBean bean : beans) {
			if (!StringUtils.startsWith(bean.getUrl(), "http://")) {
				bean.setUrl("http://" + bean.getUrl());
			}

			String hql = getHQL(yyyyMMdd, bean);

			String[] hqlParams = new String[] { hql };
			shellExecutor.excecute(money24UrlStatCreateHQLShell, hqlParams);

			String[] urls = UrlParser.parse(bean.getUrl());
			String[] params = new String[] { yyyyMMdd, output,
					Integer.valueOf(bean.getId()).toString(), urls[0],
					"".equals(urls[1]) ? "^_^" : urls[1],
					"".equals(urls[2]) ? "^_^" : urls[2],
					Integer.valueOf(bean.getMatchType()).toString(),
					bean.getUrlType() };

			shellExecutor.excecute(shell, params);
		}

	}

	public String getHQL(String yyyyMMdd, Money24UrlBean bean) {
		StringBuilder sb = new StringBuilder(
				"select log_date, count(*), count(distinct(juid)), count(distinct(ip)) ");
		boolean isUrl = true;

		if ("url".equals(bean.getUrlType())) {
			sb.append(" from 24money.pv where log_date='" + yyyyMMdd + "' and ");
		} else {
			isUrl = false;
			sb.append(" from 24money.pv where log_date='" + yyyyMMdd + "' and ");
		}

		if (bean.getMatchType() == 1) {
			if (isUrl) {
				sb.append(" url='" + bean.getUrl() + "' group by log_date");
			} else {
				sb.append(" referurl='" + bean.getUrl() + "' group by log_date");
			}
		} else {
			if (isUrl) {
				sb.append(" url like '" + bean.getUrl()
						+ "%' group by log_date");
			} else {
				sb.append(" referurl like '" + bean.getUrl()
						+ "%' group by log_date");
			}
		}

		System.out.println(sb.toString());
		return sb.toString();
	}
}
